<template>
	<view class="content">
		<view class="main backColor" v-if="">
			<view class="avatar">
				<view class="upload">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1">
						<!-- 插槽 -->
						<u-avatar :src="avatarUrl" size="60"></u-avatar>
					</u-upload>
				</view>
			</view>
			<view class="nickName" @click="gotoUserAdmin()">
				<u--text :text="nickName" align="center"></u--text>
			</view>
		</view>
		<!-- 登录按钮 -->
		<view class="loginButton backColor" v-show="loginButtonShowStatus">
			<u-button type="primary" text="登录" @click.native="login()" color="#1ba784" shape="circle"
				icon="account"></u-button>
		</view>
		<!-- 单元格 -->
		<view class="functionAndSuggestion backColor">
			<u-cell-group title="功能与反馈" :customStyle="customStyles">
				<u-cell title="个人信息" icon="man-add" :clickable="true" :isLink="true"
					@click.native="gotoUserAdmin()"></u-cell>
				<u-cell title="历史记录" icon="clock" :clickable="true" :isLink="true"
					@click.native="localHistory()"></u-cell>
				<u-cell title="常见问题" icon="tags" :clickable="true" :isLink="true" @click.native="faqs()"></u-cell>
				<u-cell title="问题反馈" icon="info-circle" value="建议" :clickable="true" :isLink="true"
					@click.native="suggestion()"></u-cell>
				<u-cell title="关于我们" :icon="icon.aboutAuthor" :clickable="true" :isLink="true"
					@click.native="aboutAuthor()"></u-cell>
			</u-cell-group>
		</view>
		<!-- 填写调查报告等 -->
		<view class="survey backColor">
			<u-cell-group title="其他" :customStyle="{'font-Size':'40px'}">
				<u-cell title="健康调查报告" icon="order" :clickable="true" :isLink="true"
					@click.native="gotoSurvey()"></u-cell>
			</u-cell-group>
		</view>
		<view class="loginPattern">
			<u-modal :show="showModalStatus" :title="modalTitle" :content='modalContent' :showCancelButton="true"
				@confirm="userLoginConfirm()" @cancel="defaultLoginConfirm()" :confirmText="confirmText"
				:cancelText="cancelText" confirmColor="#1ba784" :closeOnClickOverlay="true"
				@close="closeModal()"></u-modal>
		</view>
	</view>
</template>

<script>
	// 引入基本的url和context路径
	import {
		baseContext,
		baseUrl
	} from "@/api/index.js"
	// 引入token解析工具
	import jwt_decode from "jwt-decode"
	// 引入七牛云js
	const qiniuUploader = require("../../utils/qiniuUploader.js");
	// 初始化七牛云相关配置
	function initQiniu() {
		var options = {
			region: 'SCN',
			uptokenURL: `${baseUrl}${baseContext}/api/uptoken`,
			// uptokenFunc: function() {
			// 	return qiniuUploadToken;
			// },
			uploadFile: "https://up-z2.qiniup.com",
			domain: 'https://oss.tzfcw.top',

			shouldUseQiniuFileName: true
		};
		// 将七牛云相关配置初始化进本sdk
		qiniuUploader.init(options);
	};
	initQiniu();
	export default {
		data() {
			return {
				//单元额外样式
				customStyles: {
					// backgroundColor: "#f6f6f4",
				},
				//字体图标
				icon: {
					aboutAuthor: "https://oss.tzfcw.top/older/images/icon/wode.png",
				},
				avatarUrl: "",
				nickName: "未登录",
				loginButtonShowStatus: true,
				//更改图片数组
				fileList1: [],
				showModalStatus: false,
				modalTitle: "登录",
				modalContent: "选择你的登录方式,游客登录数据保存在本地",
				confirmText: "用户注册登录",
				cancelText: "游客登录",
				//判断用户信息是否修改
				isUpdate: false
			};
		},
		onPullDownRefresh() {
			this.readCacheForPerson();
			this.needRefreshToken();
			uni.stopPullDownRefresh()
		},
		onLoad() {
			this.readCacheForPerson();
			//绑定事件
			uni.$on("isLogin", res => {
				this.loginButtonShowStatus = !res;
			})
			//调用是否需要刷新token方法
			this.needRefreshToken();
		},
		onShow() {
			this.readCacheForPerson();
		},
		methods: {
			//封装是否刷新token的方法
			needRefreshToken() {
				if (uni.getStorageSync("token")) {
					// 判断token是否过期,过期刷新token
					const parseToken = jwt_decode(uni.getStorageSync("token"));
					// 打印解析的token所得到的过期时间
					const expireTime = parseToken.exp;
					//获取当前系统时间
					const timeStamp = Math.floor(new Date().getTime() / 1000);
					console.log(expireTime)
					console.log(timeStamp)
					//判断时间大小,以判定token是否过期
					if (timeStamp > expireTime) {
						// console.log(true)
						this.refreshToken(uni.getStorageSync("refreshToken"))
					}
				}
			},
			//发送刷新token请求方法
			refreshToken(refreshToken) {
				this.$request("/user/refreshToken", "GET", {
					"refreshToken": refreshToken
				}, {
					"refreshToken": refreshToken
				}).then(res => {
					console.log(res);
				}).catch(error => {
					//如果失败,清除本地所有的缓存
					uni.clearStorageSync()
				})
			},

			//跳转到调查报告
			gotoSurvey() {
				console.log("survey......");
				uni.navigateTo({
					url: "/pages/survey/survey"
				})

			},
			//跳转到历史记录
			localHistory() {
				uni.navigateTo({
					url: "/pages/localHistory/localHistory"
				})
			},
			//跳转到常见问题页面
			faqs() {
				uni.navigateTo({
					url: "/pages/faqs/faqs"
				})
			},
			//跳转到建议
			suggestion() {
				uni.navigateTo({
					url: "/pages/suggestion/suggestion"
				})
			},
			closeModal() {
				this.showModalStatus = false;
			},
			userLoginConfirm() {
				this.showModalStatus = false;
				// console.log("user");
				uni.navigateTo({
					url: "/pages/login/login"
				})
			},
			defaultLoginConfirm() {
				this.showModalStatus = false;
				uni.getUserProfile({
					desc: "用于完善用户个人信息",
					success: (data) => {
						this.avatarUrl = data.userInfo.avatarUrl;
						this.nickName = data.userInfo.nickName;
						this.loginButtonShowStatus = false;
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length;
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				//更新缓存
			},
			//上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					qiniuUploader.upload(url, (res) => {
						this.avatarUrl = res.fileURL;
						//读缓存
						let person = uni.getStorageSync("personInfo");
						person.avatarUrl = res.fileURL;
						//存缓存
						uni.setStorage({
							key: "personInfo",
							data: person
						})
						//发送修改请求
						this.$request("/user/update", "PUT", {
							id: person.id,
							name: person.nickName,
							avatarUrl: person.avatarUrl,
							sex: person.sex,
							phone: person.phone,
						}, {
							'content-type': "application/json",
							//携带token请求头,测试
							token: uni.getStorageSync("token")
						}).then(res => {
							console.log(`${res.data.message}`);
						}).catch(error => {
							console.log(`${error.data.message}`);
						})
					})

				})
			},
			//读取缓存
			readCacheForPerson() {
				let personInfo = uni.getStorageSync("personInfo");
				//如果缓存不为空,则让登录按钮不显示
				if (personInfo) {
					this.loginButtonShowStatus = false;
				} else {
					this.loginButtonShowStatus = true;
				}
				this.nickName = personInfo.nickName;
				this.avatarUrl = personInfo.avatarUrl;
				return personInfo;
			},
			aboutAuthor() {
				uni.navigateTo({
					url: "/pages/aboutAuthor/aboutAuthor"
				})
			},
			//前往个人信息主页
			gotoUserAdmin() {
				//如果用户登录可查看个人信息主页
				if (uni.getStorageSync("personInfo")) {
					uni.navigateTo({
						url: "/pages/PersonalInformation/PersonalInformation"
					})
				}
			},
			login() {
				//登录选择
				this.showModalStatus = true;
			}
		},
		options: {
			styleIsolation: "shared"
		},

	}
</script>

<style lang="scss" scoped>
	.backColor {
		background-color: #ffffff;
	}

	.content {
		.functionAndSuggestion {
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			border-bottom-right-radius: 18rpx;
			border-bottom-left-radius: 18rpx;
		}

		.survey {
			margin-top: 5%;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			border-bottom-right-radius: 18rpx;
			border-bottom-left-radius: 18rpx;
		}
	}

	.content ::v-deep .loginButton {
		padding: 0% 30%;
	}

	.content ::v-deep .main {
		position: relative;
		height: 220rpx;
		background: linear-gradient(17deg, #fff1eb 58%, #ace0f9 98%);
	}

	.content .main ::v-deep .avatar {
		position: absolute;
		left: 50%;
		margin-top: 5%;
		margin-left: -30px;
	}

	.content .main ::v-deep .nickName {
		position: absolute;
		width: 120px;
		font-size: 14px;
		height: 20px;
		left: 50%;
		margin-top: 22%;
		margin-left: -60px;
		font-weight: 500;
	}

	.main {}

	page {
		background-color: #f6f6f4;
	}
</style>